package ajakuulauku;

import java.util.ArrayList;

public class Physics {
	
	/**
	 * The amount of speed to be reduced every update
	 */
	double decel;
	
	/**
	 * The Ball's current location, kept in Vector2 for convenience
	 */
	private Vector2 coord;
	
	/**
	 * The Ball's movement vector
	 */
	private Vector2 momentum;
	
	/**
	 * The Ball's Mass
	 */
	private double mass;
		
	/**
	 * Manages a Ball's moving tasks
	 * @param m the ball's mass, double
	 * @param f friction, double
	 */
	public Physics(double m, double f) {
		double friction = f;
		mass = m;
		setDecel(friction, mass);
		momentum = new Vector2(0, 0);
		coord = new Vector2(0, 0);
	}
	
	/**
	 * Calculates the ball's change in coordinates
	 * @param X coordnate of the ball, double
	 * @param Y coordinate of the ball, double
	 * @return the change in coordinates, double[2]
	 */
	public Vector2 move(double X, double Y) {
		//momentum = momentum.normalize().multiplyBy(speed);
		
		coord = new Vector2 (X, Y);
		
		addMagnetForces();
		
		momentum = momentum.subtract(decel);
		//momentum = momentum.multiplyBy(1.001);
		if (momentum.length() < 0.03) {
			momentum.clear();
		}
		//momentum = momentum.multiplyBy(1.1);
		//speed = momentum.length();
		//System.out.println(speed);
		
		return momentum;
	}
	
	/**
	 * Adds the magnet's pushing forces to the ball's movement vector
	 */
	private void addMagnetForces() {
		Vector2 direction = new Vector2(0, 0);
		Vector2 location;
		double f;
		
		ArrayList<GameObject> magnets = CurrentLevel.objectCollections.get("magnet");
		Magnet mag;
		for (int i = 0; i < magnets.size(); i++) {
			if (CurrentLevel.activated.contains(i)){
				//CurrentLevel.activated.remove(i);
				mag = (Magnet)magnets.get(i);
				location = new Vector2(mag);
				direction = coord.subtract(location);
				
				f = (mag.getForce() / Math.pow(direction.length() / 2, 2)) / mass;
				
				direction = direction.normalize();
				direction = direction.multiplyBy(f);

				
				momentum = momentum.add(direction);

			}
			
		}
	}
	
	public double getSpeed() {
		return momentum.length();
	}

	
	public Vector2 getMomentum() {
		return momentum;
	}
	
	public void setMomentum(Vector2 a) {
		momentum.X = a.X;
		momentum.Y = a.Y;
	}
	
	public double getMass() {
		return this.mass;
	}
	
	public Vector2 getCoord() {
		return coord;
	}
	
	public void setCoord(Vector2 crd) {
		this.coord = crd;
	}
	
	/**
	 * Calculates the force to slow the ball down
	 * @param mju coefficient of friction, double
	 * @param mass the Ball's mass, double
	 */
	public void setDecel (double mju, double mass) {
		decel = mju * mass * 9.8;
	}
}
